package com.tencent.welink.api.base;


import com.alibaba.fastjson.JSONObject;
import com.tencent.welink.util.HttpPoolUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.ParseException;
import org.apache.http.entity.ContentType;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by junchihe on 2020/6/5.
 */
public abstract  class Api {
    private static final Logger log = LogManager.getLogger(WelinkOpenApi.class);
    // private String url;
    public final String httpPreFix;
    public boolean isGet;
    private JSONObject jsonObject = new JSONObject();
    private Map<String,Object> extendsPara = new HashMap<>();


    //头部参数
    private Map<String,Object> headerPara = new HashMap<>();
    private final ContentType contentType;

    public Api(String httpPreFix,boolean isGet){
        this(httpPreFix,isGet,ContentType.APPLICATION_JSON);
    }

    public Api(String httpPreFix,boolean isGet,ContentType contentType){
        this.httpPreFix = httpPreFix;
        this.isGet = isGet;
        this.contentType = contentType;
    }

    public abstract   String getUrl() ;

    public abstract  void displayResult(String result);

    private  String doResultByHttpPost(String bodyData,ContentType contentType) {
        try {
            String url = getUrl();
            String para = doGetUrl();
            if(StringUtils.isNotBlank(para)) {
                url = url + para;
            }
            String result = HttpPoolUtils.httpPost(url, bodyData,contentType,getHeader());
            /*JSONObject jsonObject = JSON.parseObject(result);
            //System.out.println(result);
            if (jsonObject != null && jsonObject.containsKey("code") && jsonObject.getIntValue("code") == 0
                    && jsonObject.containsKey("data") && jsonObject.get("data")!=null) {
                return jsonObject.get("data").toString();
            }*/
            log.info("url={}",url);
            log.info("bodyData={}",bodyData);
            log.info("result={}",result);
            displayResult(result);
        }catch (Exception e) {
            log.error(e);
        }
        return null;
    }

    private  String doResultByHttpPost() {
        return doResultByHttpPost(getPostBodyData(),this.contentType);
    }

    private String getPostBodyData(){
        if(jsonObject.keySet().size()==1 && jsonObject.get("")!=null){
            return jsonObject.get("").toString();
        }
        return jsonObject.toJSONString();
    }

    public Map<String, Object> getHeaderPara() {
        return headerPara;
    }


    public JSONObject getBodyPara() {
        return jsonObject;
    }

    /**
     * 获取请求头
     * @return
     */
    private Header[] getHeader(){
        Header[] headers = null;
        if(!headerPara.isEmpty()) {
            headers = new Header[headerPara.size()];
            int i = 0;
            for (Map.Entry entry : headerPara.entrySet()) {
                    headers[i++] = new Header() {
                        @Override
                        public String getName() {
                            return (String) entry.getKey();
                        }

                        @Override
                        public String getValue() {
                            return (String) entry.getValue();
                        }

                        @Override
                        public HeaderElement[] getElements() throws ParseException {
                            return new HeaderElement[0];
                        }
                    };
            }
        }
        return headers;
    }

    private String doGetUrl(){
        Map<String,Object> map = getExtendsPara();
        String url = "";
        if(map!=null && !map.isEmpty()) {
            for (Map.Entry entry : map.entrySet()) {
                try {
                    url += "&" + entry.getKey() + "=" + URLEncoder.encode(entry.getValue().toString(), "utf-8");
                }catch (Exception e){
                    log.error(e);
                }
            }
        }
        return url;
    }

    public Map<String,Object> getExtendsPara() {
        return extendsPara;
    }

    private String doResultByHttpGet(){
        /*if(map!=null && !map.isEmpty()) {
            url = getUrl() ;
            for(Map.Entry entry: map.entrySet()) {
                url += "&" + entry.getKey()+"=" + entry.getValue();
            }
        }*/
        String url = getUrl();
        String para = doGetUrl();
        if(StringUtils.isNotBlank(para)) {
            url = url + para;
        }
        String result = HttpPoolUtils.httpGet(url,getHeader());
        log.info("url={}",url);
        log.info("result={}",result);
        displayResult(result);
        return result;
    }

    public String DoHttp() {
        if(isGet) {
            return doResultByHttpGet();
        } else {
            return  doResultByHttpPost();
        }
    }

}
